﻿/*
Copyright (c) 2013, Bartłomiej Gałkowski
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met: 

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace PyroGen
{
    public class Position
    {
        public readonly int Length;
        public readonly int Location;
        public readonly Terminator StartStopType;
        public readonly CodeType Type;

        public Position(int location, CodeType type, Terminator startStopType)
            : this(location, 0, type, startStopType)
        {
        }

        public Position(int location, int length, CodeType type, Terminator startStopType)
        {
            Location = location;
            Length = length;
            Type = type;
            StartStopType = startStopType;
        }

        public Position(int location, int length, Tuple<CodeType, Terminator> type)
            : this(location, length, type.Item1, type.Item2)
        {
        }

        public int End
        {
            get { return Location + Length; }
        }

        public int Start
        {
            get { return Location; }
        }

        public new string ToString()
        {
            return "(<" + Location + "> " + Type + " " + StartStopType + ")";
        }


        public bool Overlaps(Position position)
        {
            if (Length == 0 || position.Length == 0)
                return false;
            int startRight;
            int stopLeft;

            if (Start < position.Start)
            {
                startRight = position.Start;
                stopLeft = End;
            }
            else
            {
                startRight = Start;
                stopLeft = position.End;
            }


            if (stopLeft > startRight)
                return true;
            else
                return false;
        }
    }

    public class PositionFinder
    {
        public readonly List<Position> BorderPositions;
        public readonly string ProtoText;

        public PositionFinder(string text)
        {
            BorderPositions = new List<Position>();
            ProtoText = text;
        }

        public void RemoveAll()
        {
            BorderPositions.Clear();
        }

        public void DebugPrint()
        {
            Debug.Assert(ProtoText != null);
            Debug.WriteLine("PositionFinder: numPositions = " + BorderPositions.Count);
            Debug.Indent();
            foreach (Position p in BorderPositions)
                Debug.WriteLine(p.ToString());
            Debug.Unindent();
        }


        public void AddAllPositions(Dictionary<string, Tuple<CodeType, Terminator>> positionDescr)
        {
            if(ProtoText == null)
                return;

            foreach (string delimTag in positionDescr.Keys)
            {
                AddBorderPositionsOfType(delimTag, positionDescr[delimTag]);
            }

            AddStartEndPositions();
        }

        private void SortPositions()
        {
            BorderPositions.Sort(delegate(Position a, Position b) { return a.Location - b.Location; });
        }

        private bool HasOverlapingPosition(Position newPosition)
        {
            foreach (Position bPos in BorderPositions)
                if (bPos.Overlaps(newPosition))
                    return true;
            return false;
        }

        private void AddBorderPositionsOfType(string tag, Tuple<CodeType, Terminator> positionDescr)
        {


            foreach (Match mtch in Regex.Matches(ProtoText, Regex.Escape(tag)))
            {
                Position newPosition = new Position(mtch.Index, mtch.Length, positionDescr);
                if (!HasOverlapingPosition(newPosition))
                    BorderPositions.Add(newPosition);
            }
            SortPositions();
        }

        private void AddStartEndPositions()
        {
            Debug.Assert(ProtoText != null);

            BorderPositions.Add(new Position(0, CodeType.Text, Terminator.Start));
            BorderPositions.Add(new Position(ProtoText.Length, CodeType.Text, Terminator.End));
            SortPositions();
        }
    }
}